package com.zilu.digitaltwin.common.exception;

import com.fasterxml.jackson.core.JsonProcessingException;
import com.fasterxml.jackson.databind.ObjectMapper;

import java.io.Serializable;

/**
 * @author :caijianbao
 * @date : 2023/1/2 22:41
 */
public class CommonException extends RuntimeException implements Serializable {

    private ICommonErrorCode errorCode;

    public CommonException(ICommonErrorCode errorCode) {
        this.errorCode = errorCode;
    }

    public CommonException(ICommonErrorCode errorCode, String errorMessage) {
        super(errorMessage);
        this.errorCode = errorCode;
    }

    public CommonException(ICommonErrorCode errorCode, String errorMessage, Throwable cause) {
        super(errorMessage, cause);
        this.errorCode = errorCode;
    }

    public CommonException(ICommonErrorCode errorCode, Throwable cause) {
        super(cause);
        this.errorCode = errorCode;
    }

    public String getCode() {
        return this.errorCode.getCode();
    }

    public Integer getCodeNumber() {
        return this.errorCode.getCodeNumber();
    }

    @Override
    public String getMessage() {
        return super.getMessage() == null ? this.getErrorCode().getMessage() : super.getMessage();
    }

    public ICommonErrorCode getErrorCode() {
        return this.errorCode;
    }

    public String toJSON() throws JsonProcessingException {
        ObjectMapper mapper = new ObjectMapper();
        return mapper.writeValueAsString(this);
    }
}
